package repo

import (
	"coupons/repo/model"
	"time"

	"gorm.io/gorm"
)

type OrderRepo struct {
	db *gorm.DB
}

func NewOrderRepo(db *gorm.DB) *OrderRepo {
	return &OrderRepo{
		db: db,
	}
}

// CreateOrder 创建订单
func (r *OrderRepo) CreateOrder(order *model.VoucherOrder) error {
	return r.db.Create(order).Error
}

// GetOrderById 根据Id获取订单
func (r *OrderRepo) GetOrderById(id int64) (*model.VoucherOrder, error) {
	var order model.VoucherOrder
	err := r.db.Where("id = ?", id).First(&order).Error
	if err != nil {
		return nil, err
	}
	return &order, nil
}

// GetOrdersByUserId 根据用户Id获取订单列表
func (r *OrderRepo) GetOrdersByUserId(userId string) ([]*model.VoucherOrder, error) {
	var orders []*model.VoucherOrder
	err := r.db.Where("user_id = ?", userId).Find(&orders).Error
	return orders, err
}

// GetUnusedOrdersByUserId 根据用户Id获取未使用的订单列表
func (r *OrderRepo) GetUnusedOrdersByUserId(userId string) ([]*model.VoucherOrder, error) {
	var orders []*model.VoucherOrder
	err := r.db.Where("user_id = ? AND status = ?", userId, model.OrderStatusUnused).Find(&orders).Error
	return orders, err
}

// UseVoucherByVoucherId 根据用户ID和优惠券ID使用优惠券
func (r *OrderRepo) UseVoucherByVoucherId(userId string, voucherId string) error {
	return r.db.Model(&model.VoucherOrder{}).Where("user_id = ? AND voucher_id = ? AND status = ?", userId, voucherId, model.OrderStatusUnused).Updates(map[string]interface{}{
		"status":   model.OrderStatusUsed,
		"use_time": time.Now(),
	}).Error
}
